package com.financial.service.yspay.service.impl;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.constants.YsServiceEnumConstants;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayBuildRequestParaService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.service.FinancialYsRefundService;
import com.financial.service.yspay.utils.DateUtils;
import com.financial.service.yspay.utils.HttpUtils;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Davidbieber
 * @description 银盛退款接口实现类
 * @email davidbieber@163.com
 * @date 2019/11/20 8:41 AM
 */
@Service
public class FinancialYsRefundServiceImpl implements FinancialYsRefundService {

    protected static final Logger logger= LoggerFactory.getLogger(FinancialYsRefundServiceImpl.class);

    @Value("${ysRefundMethod}")
    private String ysRefundMethod;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private FinancialYsPayBuildRequestParaService financialYsPayBuildRequestParaService;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    @Override
    public ApiResult ysRefund(String requestParam) {
        logger.error("FinancialysRefundServiceImpl.ysRefund()------银盛退款请求参数json为:"+requestParam);
        String ysPayRefundJson=sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsRefundDTO= JsonUtils.parseObject(ysPayRefundJson);        /*返回内容初始化*/
        String content = null;
        if (financialYsRefundDTO != null) {
            /*组装银盛微信支付参数信息*/
            Map<String, String> param = new HashMap<>();
            param.put("method", ysRefundMethod);
            param.put("partner_id", financialYsRefundDTO.getPARTNER_ID());
            param.put("timestamp", DateUtils.getNowTimeStr());
            param.put("charset", financialYsRefundDTO.getDEFAULT_CHARSET());
            param.put("sign_type", financialYsRefundDTO.getSIGN_ALGORITHM());
            param.put("version", financialYsRefundDTO.getVERSION());
            param.put("biz_content",requestParam);
            logger.info("FinancialYsRefundServiceImpl.ysRefund()----->请求银盛退款参数为:" + param.toString());
            try {
                //签名
                Map<String, String> sPara = financialYsPayBuildRequestParaService.buildRequestPara(param, financialYsRefundDTO);
                //发起请求
                logger.info("FinancialYsRefundServiceImpl.ysRefund()----->签名完成的参数：", sPara);
                String returnString = HttpUtils.httpsSend(financialYsRefundDTO.getYSEPAY_GATEWAY_URL(), sPara);
                logger.info("FinancialYsRefundServiceImpl.ysRefund()----->银盛退款请求接口参数返回数据：" + JsonUtils.objectToJson(returnString));
                //回执参数JSON转map
                Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(returnString);
                Map<String, String> obj = (Map<String, String>) resultMap.get("ysepay_online_trade_refund_split_response");
                boolean verifyResult = false;
                if (obj == null) {
                    return ApiResult.failure(JsonUtils.objectToJson("银盛退款返回结果为空"));
                }
                int begin = returnString.indexOf("ysepay_online_trade_refund_split_response");
                content = returnString.substring(begin);
                content = content.replace("ysepay_online_trade_refund_split_response", "");
                content = content.substring(2, content.length() - 1);
                verifyResult = financialYsPayVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), content, "utf-8",financialYsRefundDTO);
                logger.info("FinancialYsRefundServiceImpl.ysRefund()----->退款请求回执信息,验签是否成功:{},验签结果:{}",content,verifyResult);
                if (null == content || content.equals("")) {
                    logger.info("FinancialYsRefundServiceImpl.ysRefund()----->验签没有成功:银盛退款返回结果为空");
                    return ApiResult.failure(JsonUtils.objectToJson("银盛退款返回结果为空"));
                }
                /*解析content*/
                Map<String,Object> contentMap=JsonUtils.jsonToMap(content);
                boolean returnCodeState=contentMap.containsKey("code");
                if(returnCodeState){
                    Object tempParams=contentMap.get("code");
                    String returnCode=tempParams==null?null:tempParams.toString();
                    if(returnCode.equalsIgnoreCase(YsServiceEnumConstants.ENUM_REFUNDSTATUS_SUC)){
                        /*10000是退款成功标识*/
                        return ApiResult.success(content);
                    }else{
                        /*失败返回*/
                        return ApiResult.failure(content);
                    }
                }else{
                    /*失败返回*/
                    return ApiResult.failure(content);
                }
            } catch (IOException e) {
                logger.error("银盛分账退款接口"+e.getMessage());
                e.printStackTrace();
            } catch (IllegalAccessException e1) {
                logger.error("银盛分账退款接口"+e1.getMessage());
                e1.printStackTrace();
            } catch (Exception e2) {
                logger.error("银盛分账退款接口"+e2.getMessage());
                e2.printStackTrace();
            }
        }
        return ApiResult.failure(requestParam);
    }
}
